package com.ai.langchain4j.memory;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.dashscope.utils.JsonUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @Author: suren@517na.com
 * @CreateTime: 2025-05-26
 * @Description: 持久化历史对话
 */

@Component
public class PersistentChatMemoryStore implements ChatMemoryStore {

    private static final String MEMORY_KEY = "ai:memory:";
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    ObjectMapper objectMapper;
    @Override
    public List<ChatMessage> getMessages(Object o) {
        Object fromValue = redisTemplate.opsForValue().get(getMemoryKey(o));

        if (fromValue == null) {
            return new ArrayList<>();
        }

        return ChatMessageDeserializer.messagesFromJson(fromValue.toString());
    }

    @Override
    public void updateMessages(Object o, List<ChatMessage> list) {
        String messages = ChatMessageSerializer.messagesToJson(list);
        redisTemplate.opsForValue().set(getMemoryKey(o), messages);
    }

    @Override
    public void deleteMessages(Object o) {
        redisTemplate.delete(getMemoryKey(o));
    }

    private String getMemoryKey(Object o) {
        return MEMORY_KEY + (Integer)o;
    }
}
